<?php

namespace addons\shopro\services;

use addons\shopro\model\User;
use app\common\model\ScoreLog;
use think\Db;

/**
 * 会员服务
 * @Author ycr <E-mail:yuncran@126.com>
 */
class UserService
{
    /** @var string 用户信息 */
    const user_field = 'id,username,nickname,mobile,score,jointime,status';

    /** 会员扣除积分 */
    public function userScore(int $uid, float $decScore)
    {
        // 启动事务
        Db::startTrans();
        try {
            $user_where = ['id' => $uid, 'status' => 'normal'];
            $user = User::where($user_where)->find(self::user_field);

            $user = User::where(['id' => $uid])->setDec('score', $decScore);
            /** @var  $user_log 积分消费记录 */
            $data = [
                'user_id' => $uid,
                'score' => $decScore,

                'before' => $decScore,
                'after' => $decScore,
                'memo' => $decScore,
            ];
            $user_log = ScoreLog::create();
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            \think\Log::write('user_score:' . json_encode($e->getMessage()));
            // 回滚事务
            Db::rollback();

        }
    }
}